#include "link.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "mqtt.h"
#include <signal.h>
#include <json-c/json.h>
#include "main.h"
#include <time.h>
#include <unistd.h>

extern tLink *head;

void init_link()
{
	head = (tLink *)malloc(sizeof(tLink));
	if (NULL == head)
	{
		perror("malloc");
		return;
	}

	head->next = NULL;
}

void add_link(int fd, const char *t)
{
	tLink *p = head;

	while (p->next)
		p = p->next;

	tLink *newNode = (tLink *)malloc(sizeof(tLink));
	if (NULL == newNode)
	{
		perror("malloc");
		return;
	}

	newNode->fd = fd;
	strcpy(newNode->topic, t);
	newNode->next = NULL;

	p->next = newNode;
}

void send_message(const char *topic, const char *msg, int MsgLen)
{
	tLink *p = head->next;

	while (p)
	{
		if (!strcmp(p->topic, topic))
		{
			message_publish(p->fd, topic, msg, MsgLen);
		}

		p = p->next;
	}
}

void delete_link(int fd)
{
	tLink *p = head;

	while (p->next)
	{
		if (p->next->fd == fd)
		{
			tLink *DelNode = p->next;
			p->next = DelNode->next;
			free(DelNode);
		}
		else
		{
			p = p->next;
		}
	}
}

void update_device_time(int sig)
{
	tLink *p = head->next;
	time_t t = time(NULL);

	while (p)
	{
		if (strstr(p->topic, "upload"))
		{
			p = p->next;
			continue;
		}

		struct json_object *obj = json_object_new_object();
		json_object_object_add(obj, "cmd", json_object_new_string("date"));
		json_object_object_add(obj, "time", json_object_new_int(t));
		const char *msg = json_object_to_json_string(obj);

		message_publish(p->fd, p->topic, msg, strlen(msg));

		p = p->next;
	}

	alarm(TIMEOUT);
}
